<template>
  <a-modal :open="pageData.show" :width="1500"  @cancel="onClose(null)" :centered="true" :footer="null" :maskClosable="false">
    <template #title>{{ modalParam.modalTitle }}</template>
    <div class="page-detail">
      <div class="panel-search" style="display: flex; width: 100%;">
        <div style="flex: 1;display: flex;flex-wrap: wrap;justify-content: space-around;">
          <div class="search-item item-bottom" style="margin-right: 10px;">
            <label style="width: 80px; padding-right: 10px;">消息内容:</label>
            <a-input v-model:value="searchData.searchableKey" style="width: 160px;" placeholder="请输入消息内容" @pressEnter="onSearch" allow-clear/>
          </div>
          <div class="search-item item-bottom" style="margin-right: 10px;">
            <label style="width: 60px;padding-right: 10px;">时间:</label>
<!--            <a-range-picker v-model:value="searchData.range" picker="month" />-->
            <a-range-picker  v-model:value="searchData.range" style="width: 250px;" @pressEnter="onSearch" allow-clear></a-range-picker>
          </div>
          <div class="search-item item-bottom" style="margin-right: 10px;">
            <label style="width: 80px;padding-right: 10px;">会话类型:</label>
            <a-select v-model:value="searchData.type" style="width: 150px;" placeholder="请选择" @change="onTypeChange">
              <a-select-option value="群聊">群聊</a-select-option>
              <a-select-option value="单聊">单聊</a-select-option>
            </a-select>
          </div>
          <div class="search-item item-bottom" style="margin-right: 10px;">
            <label style="width: 80px;padding-right: 10px;">消息类型:</label>
            <a-select v-model:value="searchData.contentType" style="width: 180px;" placeholder="请选择" @change="onContentTypeChange">
              <a-select-option value="文本">文本</a-select-option>
              <a-select-option value="图片">图片</a-select-option>
              <a-select-option value="视频">视频</a-select-option>
              <a-select-option value="语音">语音</a-select-option>
              <a-select-option value="文件">文件</a-select-option>
            </a-select>
          </div>
          <div class="search-item item-bottom" style="margin-right: 10px;">
            <label style="width: 90px;padding-right: 10px;">发送者昵称:</label>
            <a-input v-model:value="searchData.senderName" style="width: 150px;" placeholder="请输入发送者昵称" @pressEnter="onSearch" allow-clear/>
          </div>
          <div class="search-item item-bottom" style="margin-right: 10px;">
            <label style="width: 100px;padding-right: 10px;">接收者昵称:</label>
            <a-input v-model:value="searchData.receiverName" style="width: 210px;" placeholder="请输入接收者昵称" @pressEnter="onSearch" allow-clear/>
          </div>
          <div class="search-item item-bottom" style="margin-right: 10px;">
            <label style="width: 80px;padding-right: 10px;">发送者ID:</label>
            <a-input v-model:value="searchData.senderId" style="width: 150px;" placeholder="请输入发送者ID" @pressEnter="onSearch" allow-clear/>
          </div>
          <div class="search-item item-bottom" style="margin-right: 10px;">
            <label style="width: 80px;padding-right: 10px;">接收者ID:</label>
            <a-input v-model:value="searchData.receiverId" style="width: 180px;" placeholder="请输入接收者ID" @pressEnter="onSearch" allow-clear/>
          </div>
        </div>
        <div style="width: 200px">
          <!-- 查询和重置按钮 -->
          <div class="search-btn" style="display: flex; justify-content: flex-end; width: 100%;margin-right: 10px;">
            <a-button type="primary" @click="onSearch" style="margin-right: 10px;">查询</a-button>
            <a-button @click="onReset" style="margin-right: 10px;">重置</a-button>
          </div>
        </div>
      </div>
      <div class="panel-table">
        <div class="panel-table-tool">
          <div class="tool-btn" style="display: flex; justify-content: flex-start;margin-top: 10px; width: 100%;">
<!--            <a-button @click="onDelete(null)" type="primary" ghost>批量删除</a-button>-->
            <a-button @click="onExport(null)" type="primary" >导出</a-button>
          </div>
        </div>
        <div class="panel-table-list">
          <a-table :bordered="true" :data-source="tableData.data" :columns="tableData.columns"
                   :loading="tableData.loading" :pagination="false" :scroll="{x: 1315}"
                   :rowKey="(record) => record.id"
                   >
            <template #bodyCell="{ text, record, index, column }">
              <!-- 添加对消息类型的特殊处理 -->
              <template v-if="column.key && column.key === 'messageType'">
                <a-tag :color="getMessageTypeColor(text)">
                  {{  getMessageTypeText(text) }}
                </a-tag>
              </template>
              <!-- 添加对消息内容的特殊处理 -->
              <template v-if="column.key && column.key === 'content'">
                <!--              <div v-if="record.messageType === 1">{{ text }}</div>-->
                <div v-if="record.messageType === 3 || record.messageType === 7">
                  <!-- 显示图片 -->
                  <img :src="record.content" alt="图片" style="max-width: 100%; max-height: 100px;">
                </div>
                <div v-else-if="record.messageType === 2 || record.messageType === 23">
                  <a  @click="onPlayAmr(record.content)" target="_blank" >点击播放音频</a>
<!--                  <a :href="record.content" target="_blank" >点击下载音频</a>-->
<!--                  &lt;!&ndash; 播放音频 &ndash;&gt;-->
<!--                  <audio  :src="record.content" style="width: 200px;height:50px;cursor: pointer;" controls></audio>-->
                </div>
                <div v-else-if="record.messageType === 6">
                  <!-- 播放视频 -->
                  <video :src="record.content"  style="width: 200px;height:100px;cursor: pointer;" controls></video>
                </div>
                <div v-else-if="record.messageType === 5">
                  <!-- 文件下载链接 -->
                  <a :href="record.content" target="_blank" class="file-name">{{ record.fileName }}</a>
                </div>
              </template>

            </template>
          </a-table>
        </div>
        <div class="panel-table-pager" style="display: flex; justify-content: flex-end;margin-top: 10px">
          <a-pagination :current="pagerData.current" :pageSize="pagerData.pageSize" :total="pagerData.total" :show-total="total => '共' + total + '条'"
                        @showSizeChange="onPagerSizeChange" @change="onPagerChange" show-quick-jumper show-size-changer>
          </a-pagination>

        </div>
      </div>
    </div>

  </a-modal>
</template>

<script>



import BenzAMRRecorder from "benz-amr-recorder";

export default {
  components: {

  },
  props: {modalParam: {type: Object},
    messageType: {type: String, required: true,},
  },

  data() {
    return {
      searchData: {
        senderName: '', // 发送者昵称
        receiverName: '', // 接收者昵称
        senderId: '', // 发送者ID，支持模糊查询
        receiverId: '', // 接收者ID，支持模糊查询
        type: null, // 会话类型，群聊或单聊 0为单聊 1为群聊
        searchableKey: '', // 消息内容，支持模糊查询
        contentType: null, // 消息类型，文本、图片、视频、语音
        page: 1, // 当前页码
        pageSize: 10, // 每页展示的数据条数
        range: [null, null], // 起始时间和终止时间的数组
      },

      pageData: {
        show: true,
        loading: false,
      },
      modalData: {
        showDetail: false,
        data: null
      },
      orgList: [],
      tableData: {
        loading: false, selectedRowKeys: [], data: [],
        columns: [
          { title: "序号", key: "index", width: 65, align: "center", customRender: ({ index }) => { return index + 1 } },
          { title: '会话类型', dataIndex: 'sessionType', width: 100, align: 'center', ellipsis: true ,customRender: ({ text }) => {
              return `${text === 0 ? '单聊' : (text === 1 ? '群聊' : '未知类型')}`;
            }},
          { title: '消息类型', key: "messageType", dataIndex: 'messageType', width: 100, align: 'center', ellipsis: true, customRender: ({ text }) => {
              let messageTypeText = '';
              switch (text) {
                case 1:
                  messageTypeText = '文本';
                  break;
                case 2:
                  messageTypeText = '语音';
                  break;
                case 3:
                  messageTypeText = '图片';
                  break;
                case 4:
                  messageTypeText = '视频';
                  break;
                default:
                  messageTypeText = '文本';
              }
              return `${messageTypeText}`;
            }
          },
          { title: '发送者昵称', dataIndex: 'senderNickname', width: 120, align: 'center', ellipsis: true },
          { title: '接收者昵称', dataIndex: 'receiverNickname', minWidth: 150, align: 'center', ellipsis: true },
          { title: '发送者ID', dataIndex: 'senderId', width: 110, align: 'center', ellipsis: true },
          { title: '接收者ID', dataIndex: 'receiverId', width: 110, align: 'center', ellipsis: true },
          { title: '消息内容', key:'content',dataIndex: 'content', minWidth: 150, align: 'center', ellipsis: true},
          { title: '时间', dataIndex: 'createdAt', minWidth: 150, align: 'center', ellipsis: true},

        ]
      },
      pagerData: {
        current: 1, pageSize: 10, total: 0
      }
    }
  },
  mounted() {
    // 获取传递的消息类型参数
    const messageType = this.modalParam.contentType;
    const range = this.modalParam.range;

    this.searchData.range = range;

    // 设置消息类型单选框的选中状态
    if (messageType) {
      switch (messageType) {
        case 'text':
          this.searchData.contentType = '文本';
          break;
        case 'voice':
          this.searchData.contentType = '语音';
          break;
        case 'image':
          this.searchData.contentType = '图片';
          break;
        case 'video':
          this.searchData.contentType = '视频';
          break;
        case 'file' :
          this.searchData.contentType = '文件';
          break;
      }

      // 触发查询操作，根据需要调用对应的查询方法
      // this.queryInfoData(messageType); // 请替换成实际的查询方法
    }
    this.queryPageData();
  },
  methods: {
    onPlayAmr(url){
      var amr = new BenzAMRRecorder()
      amr.initWithUrl(url).then(function() {
        amr.play()
      })
      amr.onEnded(function() {
        //alert('播放完毕')
      })
    },
    //获取页面数据
    queryPageData() {
      console.log('kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk0000')
      this.queryTableList();
    },
    getContentType(type){
      if(!type){
        return null;
      }
      switch (type){
        case '文本':
          return '1';
          break;
        case '图片':
          return '3,7';
          break;
        case '视频':
          return '6';
          break;
        case '语音':
          return '2,23';
          break;
        case '文件':
          return '5';
          break;
      }
    },

    //获取表格数据
    queryTableList() {
      // 构建请求参数
      let params = {
        senderName: this.searchData.senderName,
        receiverName: this.searchData.receiverName,
        senderId: this.searchData.senderId,
        receiverId: this.searchData.receiverId,
        searchableKey: this.searchData.searchableKey,
        page: this.pagerData.current,
        pageSize: this.pagerData.pageSize,
        type:this.searchData.type,
        contentType: this.getContentType(this.searchData.contentType),
        begin:null,
        end:null,
      };

      // 添加类型和消息类型的判断，如果不为空 则加入请求参数
      if (this.searchData.type !== null) {
        params.type = this.searchData.type === '群聊' ? 1 : 0;
      }

      // 处理日期时间范围
      if (this.searchData.range) {
        params.begin = this.formatDate(this.searchData.range[0]) ;
        params.end = this.formatDate(this.searchData.range[1]) ;
      }
      // 过滤出非空参数
      params = Object.fromEntries(Object.entries(params).filter(([key, value]) => value !== undefined && value !== null));
      // 构建 URL 字符串
      let url = `${this.$Api.messageData.queryMessageList}?${new URLSearchParams(params).toString()}`;
      this.tableData.loading = true;
      this.$ajax.get(url).then(res => {
        console.log(res);
        if(res.data.code == 200) {
          //设置表格数据
          this.tableData.data = res.data.data.map(msg => ({
            sessionType: msg._type,
            messageType: msg._content_type,
            senderNickname: msg.sender_name,
            receiverNickname: msg.receiver_name,
            senderId: msg.sender_uid,
            receiverId: msg.receiver_uid,
            content: msg._searchable_key,
            createdAt: msg._dt,
            id: msg._mid+'',
            mid: msg.midstr,
            fileName:msg.fileName
          }));
          //设置分页数据
          this.pagerData.total = res.data.count;
        }
      }).finally(() => {
        this.tableData.loading = false;
      })
    },
    //查询
    onSearch() {
      this.pagerData.current = 1;
      this.queryTableList();
    },
    //重置搜索条件
    onReset() {
      // 将 searchData 对象中的属性重置为初始值
      this.searchData.senderName = '';
      this.searchData.receiverName = '';
      this.searchData.senderId = '';
      this.searchData.receiverId = '';
      this.searchData.type = null;
      this.searchData.searchableKey = '';
      this.searchData.contentType = null;
      this.searchData.page = 1;
      this.searchData.pageSize = 10;
      this.searchData.begin = null;
      this.searchData.end = null;
      this.searchData.range = null;
      this.onSearch();
    },
    // 格式化日期的辅助方法
    formatDate(dateString) {
      // this.$dayjs(params.year).format('YYYY-MM');
      if (dateString) {
        const date = new Date(dateString);
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        return `${year}-${month}-${day}`;
      } else {
        return null;
      }
    },
    //分页页码改变
    onPagerChange(current) {
      this.pagerData.current = current;
      this.queryTableList();
    },
    //分页每页数量改变
    onPagerSizeChange(current, size) {
      this.pagerData.current = 1;
      this.pagerData.pageSize = size;
      this.queryTableList();
    },
    //查看
    onView(record) {
      const messageId = record.mid;
      console.log(messageId);
      this.modalData.showDetail = false;
      this.$nextTick(() => {
        this.modalData.data = {
          modalTitle: "查看",
          messageId: messageId, // 将消息的唯一标识传递给 modalData
        };
        this.modalData.showDetail = true;
      });
    },
    // 删除
    onDelete(record) {
      let messageIds = [];
      if (record) { // 单个删除
        messageIds.push(record.mid);
      } else { // 批量删除
        let selectedRows = _.filter(this.tableData.data, o => {
          return _.includes(this.tableData.selectedRowKeys, o.id);
        });
        messageIds = _.map(selectedRows, "mid");
      }
      console.log(messageIds+"选择的消息id数组----------");

      if (messageIds.length <= 0) {
        this.$message.warning("请选择要删除的消息！");
        return;
      }

      let params = {
        messageIds: _.join(messageIds, ","),
      };

      let _this = this;
      this.$modal.confirm({
        title: "信息提示", content: "确定要删除已选消息吗？", okText: "确定",
        onOk() {
          // 使用模板字符串构建带路径参数的URL
          let url = `${_this.$Api.messageData.deleteMessage}/${params.messageIds}`;
          _this.$ajax.post(url).then(res => {
            if (res.data.code == 0) {
              _this.$message.success("操作成功");
              _this.onSearch();
              _this.tableData.selectedRowKeys = [];
            } else {
              _this.$message.error("操作失败");
            }
          }).catch(() => {
            _this.$message.error("操作失败");
          });
        },
      });
    },
    //导出Excel表格
    onExport(){
      // 构建请求参数
      let params = {
        // 获取token from localStorage
        ticketNO:localStorage.getItem("ticketNO"),
        senderName: this.searchData.senderName,
        receiverName: this.searchData.receiverName,
        senderId: this.searchData.senderId,
        receiverId: this.searchData.receiverId,
        searchableKey: this.searchData.searchableKey,
        page: this.pagerData.current,
        pageSize: this.pagerData.pageSize,
        type: this.searchData.type,
        contentType: this.getContentType(this.searchData.contentType),
        begin: null,
        end: null,
      };

      // 添加类型和消息类型的判断，如果不为空则加入请求参数
      if (this.searchData.type !== null) {
        params.type = this.searchData.type === '群聊' ? 1 : 0;
      }

      // 处理日期时间范围
      if (this.searchData.range) {
        params.begin = this.formatDate(this.searchData.range[0]);
        params.end = this.formatDate(this.searchData.range[1]);
      }

      // 过滤出非空参数
      params = Object.fromEntries(Object.entries(params).filter(([key, value]) => value !== undefined && value !== null));

      // 获取token from localStorage
      const ticketNO = localStorage.getItem("ticketNO");
      // 构建 URL 字符串
      let url = `${this.$Api.messageData.exportMessageDataList}?${new URLSearchParams(params).toString()}`;

      window.open(
          url
      );
      // this.$Api.messageData.exportMessageDataList +"?"
    },
    //关闭弹窗
    closeModal(type, data) {
      this.modalData.data = null;
      this.modalData[type] = false;
      if (data && data.refresh) {
        this.onSearch();
      }
    },
    // //已有消息类型进行查询
    // queryInfoData(messageType){
    //   // 构建请求参数
    //   let params = {
    //     senderName: this.searchData.senderName,
    //     receiverName: this.searchData.receiverName,
    //     senderId: this.searchData.senderId,
    //     receiverId: this.searchData.receiverId,
    //     searchableKey: this.searchData.searchableKey,
    //     page: this.pagerData.current,
    //     pageSize: this.pagerData.pageSize,
    //     type:this.searchData.type,
    //     contentType:messageType,
    //     begin:null,
    //     end:null,
    //   };
    //
    //   // 添加类型和消息类型的判断，如果不为空 则加入请求参数
    //   if (this.searchData.type !== null) {
    //     params.type = this.searchData.type === '群聊' ? 1 : 0;
    //   }
    //
    //   switch (messageType) {
    //     case 'text':
    //       params.contentType = 1;
    //       break;
    //     case 'voice':
    //       params.contentType = 2;
    //       break;
    //     case 'image':
    //       params.contentType = 3;
    //       break;
    //     case 'video':
    //       params.contentType = 4;
    //       break;
    //     case 'file':
    //       params.contentType = 5;
    //       break;
    //     default:
    //       params.contentType = 1; // 默认为文本类型
    //   }
    //
    //   // 处理日期时间范围
    //   if (this.searchData.range) {
    //     params.begin = this.formatDate(this.searchData.range[0]) ;
    //     params.end = this.formatDate(this.searchData.range[1]) ;
    //   }
    //   // 过滤出非空参数
    //   params = Object.fromEntries(Object.entries(params).filter(([key, value]) => value !== undefined && value !== null));
    //   // 构建 URL 字符串
    //   let url = `${this.$Api.messageData.queryMessageList}?${new URLSearchParams(params).toString()}`;
    //   this.tableData.loading = true;
    //   this.$ajax.get(url).then(res => {
    //     if(res.data.code == 200) {
    //       console.log('res================',res)
    //       //设置表格数据
    //       this.tableData.data = res.data.data.map(msg => ({
    //         sessionType: msg._type,
    //         messageType: msg._content_type,
    //         senderNickname: msg.sender_name,
    //         receiverNickname: msg.receiver_name,
    //         senderId: msg.sender_uid,
    //         receiverId: msg.receiver_uid,
    //         content: msg._searchable_key,
    //         createdAt: msg._dt,
    //         id: msg._mid+'',
    //         mid: msg.midstr
    //       }));
    //       //设置分页数据
    //       this.pagerData.total = res.data.count;
    //     }
    //   }).finally(() => {
    //     this.tableData.loading = false;
    //   })
    // },

    // 添加获取消息类型颜色的方法，你可以根据实际需求自定义颜色逻辑
    getMessageTypeColor(type) {
      switch (type) {
        case 1:
          return 'blue'; // 文本类型使用蓝色
        case 2:
        case 23:
          return 'green'; // 语音类型使用绿色
        case 5:
          return 'cyan';//文件类型
        case 3:
        case 7:
          return 'red'; // 图片类型使用橙色
        case 6:
          return 'purple'; // 视频类型使用红色
        default:
          return 'blue'; // 其他类型使用默认颜色
      }
    },
    // 添加获取消息类型文本的方法，你可以根据实际需求自定义文本逻辑
    getMessageTypeText(type) {
      switch (type) {
        case 1:
          return '文本';
        case 2:
        case 23:
          return '语音';
        case 5:
          return '文件';
        case 3:
        case 7:
          return '图片';
        case 6:
          return '视频';
        default:
          return '文本';
      }
    },

    // 会话类型下拉框变化事件处理
    onTypeChange() {
      this.pagerData.current = 1;
      this.queryTableList();
    },

    // 消息类型下拉框变化事件处理
    onContentTypeChange() {
      this.pagerData.current = 1;
      this.queryTableList();
    },

    //关闭弹窗
    onClose(refresh) {
      this.$emit("close", {refresh: refresh});
    },


  }
}


</script>

<style scoped lang="less">

.item-bottom {
  margin-bottom: 20px;
}

</style>
